package com.gdou.controller;


import com.gdou.commons.Constants;
import com.gdou.commons.UploadBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URISyntaxException;

@Controller
@RequestMapping("/download")
public class DownloadController {

    @Autowired
    private UploadBean uploadBean;


    /*1自检： 如果 文件保存文件夹 没有默认图片 则 从项目目录中拷贝一份*/
    @ModelAttribute
    public void transferDefaultImg() throws URISyntaxException, IOException {
        /*获取默认图片 存放文件夹*/
        String saveUrl = uploadBean.getBaseUrl();
        File file = new File(saveUrl + "/" + Constants.DEFAULT_HEAD_IMG);
        if (file.exists()){//文件存在 则不需要拷贝
            return;
        }
        /*不存在*/
        File baseUrl = new File(saveUrl);
        /*文件夹 不存在*/
        if (!baseUrl.exists()){
            baseUrl.mkdirs();
        }
        /*获取 默认头像在 工程中的位置*/
        String resourcePath = this.getClass().getResource("/static/resources/images/" + Constants.DEFAULT_HEAD_IMG)
                .toURI().getPath();
        /*边读编写*/
        /*输入流*/
        FileInputStream fileInputStream = new FileInputStream(resourcePath);
        /*输出流*/
        FileOutputStream fileOutputStream = new FileOutputStream(saveUrl + "/" + Constants.DEFAULT_HEAD_IMG);
        byte[] bt = new byte[1024];
        int len = -1;
        while ((len=fileInputStream.read(bt))!=-1){
            /*下载*/
            fileOutputStream.write(bt,0,len);
        }
        fileOutputStream.close();
        fileInputStream.close();
    }

    @RequestMapping("/downloadImg")
    public void downLoad(String imgUrl, HttpServletResponse response) throws IOException {
        /*通过 response获取 输出流  输出 图片信息（文件流）*/
        if (imgUrl!=null){
            /*保存地址*/
            String saveUrl = uploadBean.getBaseUrl();
            FileInputStream fileInputStream = new FileInputStream(saveUrl + "/" + imgUrl);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bt = new byte[1024];
            int len = -1;
            while ((len=fileInputStream.read(bt))!=-1){
                /*下载*/
                /*输出流*/
                outputStream.write(bt,0,len);
            }
            outputStream.close();
            fileInputStream.close();
        }
    }

}
